<template>
  <div class="login-container">
    <el-form class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">User Login</h3>
      </div>
      <el-button :loading="loading"
                 type="primary"
                 style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="createMetaMask()">🦊  Create MetaMask Wallet</el-button>
      <el-button :loading="loading"
                 type="primary"
                 style="width:95%;margin-bottom:30px;"
                 @click.native.prevent="goEmailLogin()">Login From Email</el-button>
    </el-form>
  </div>
</template>

<script>
  import { validUsername } from '@/utils/validate'
  import SocialSign from './components/SocialSignin'

  export default {
    name: 'Login',
    components: {
      SocialSign
    },
    data() {
      return {
        capsTooltip: false,
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {}
      }
    },
    methods: {
      createMetaMask() {
        let _this = this;
        //检测当前浏览器是否以太坊兼容，并进行相应的处理
        if (typeof window.ethereum === 'undefined') {
          //this.$message('Looks like you need a Dapp browser to get started. Please install MetaMask!');
          this.$confirm('Please install MetaMask!', 'notes', {
            confirmButtonText: 'ok', cancelButtonText: 'cancel', type: 'warning'
          }).then(() => {
            window.open("https://metamask.io/")
          })
        } else {
          //如果用户安装了MetaMask，你可以要求他们授权应用登录并获取其账号
          ethereum.enable()
            //如果用户拒绝了登录请求
            .catch(function(reason) {
              if (reason === 'User rejected provider access') {
                // 用户不想登录，你看该怎么办？
                _this.$message('Login Error, Please try Again!');
              } else {
                // 本不该执行到这里，但是真到这里了，说明发生了意外
                _this.$message.error('There was an issue signing you in.');
              }
            })

            //如果用户同意了登录请求，你就可以拿到用户的账号
            .then(function(accounts) {
              //你也可以验证用户接入了正确的网络
              console.log("获取到的用户账号：",accounts,"当前网络：",ethereum.networkVersion);//return;
              if (ethereum.networkVersion != 3) {//97
                console.log("networkVersion：",ethereum.networkVersion)
                _this.$message("请检查网络地址");return;
                //我们计划在最近补充一个有关网络切换的API，参考下面链接
                // https://github.com/MetaMask/metamask-extension/issues/3663
              }

              //一旦获取了用户账号，你就可以签名交易
              const account = accounts[0]
              sendEtherFrom(account, function(err, transaction) {
                if (err) {
                  return alert(`Sorry you weren't able to contribute!`)
                }
                alert('Thanks for your successful contribution!')
              })

            })
        }

        function sendEtherFrom(account, callback) {
          var value = "0.000061";
          var value = _this.web3.utils.toWei(value, 'ether');
          var valu1 = _this.web3.utils.toHex(value)
          console.log(valu1);
          //return;
          //在这里我们要使用底层API
          const method = 'eth_sendTransaction'
          const parameters = [{
            from: account,
            to: "0xe913956474F57Dca95eE5AB28c5d178846499Be1",
            value: valu1,
          }]
          //console.log(parameters);return;
          const from = account;

          //现在把所有数据整合为一个RPC请求
          const payload = {
            method: method,
            params: parameters,
            from: from,
          }
          // _this.web3.eth.sendTransaction(payload, function(err, response) {
          //   console.log(err)
          //   console.log(response)
          // });
          // return;
          //需要用户授权的方法，类似于这个，都会弹出一个对话框提醒用户交互
          //其他方法，例如只是读取区块链的数据，可能就不会弹框提醒
          ethereum.sendAsync(payload, function(err, response) {
            const rejected = 'User denied transaction signature.'
            console.log("payload:",payload);return;
            if (response.error && response.error.message.includes(rejected)) {
              _this.$message(`用户拒绝授权操作`);return;
            }

            if (err) {
              console.log("ethereum.sendAsync-err:",err)
              return alert('There was an issue, please try again.')
            }

            if (response.result) {
              //如果存在response.result，那么调用就是成功的
              //在这种情况下，它就是交易哈希
              const txHash = response.result
              alert('Thank you for your generosity!')

              //你可以轮询区块链来查看交易何时被打包进区块
              pollForCompletion(txHash, callback)
            }
          })
        }

        function pollForCompletion(txHash, callback) {
          let calledBack = false

          //正常情况下，以太坊区块大约15秒钟出一块
          //这里我们每隔2秒钟轮询一次
          const checkInterval = setInterval(function() {

            const notYet = 'response has no error or result'
            ethereum.sendAsync({
              method: 'eth_getTransactionByHash',
              params: [txHash],
            }, function(err, response) {
              if (calledBack) return
              if (err || response.error) {
                if (err.message.includes(notYet)) {
                  return 'transaction is not yet mined'
                }

                callback(err || response.error)
              }

              //我们已经成功地验证了打包入块的交易
              //提醒一下，我们应当在服务端使用我们的区块链连接进行验证
              //在客户端做的话，就意味着我们信任用户的区块链连接
              const transaction = response.result
              clearInterval(checkInterval)
              calledBack = true
              callback(null, transaction)
            })
          }, 2000)
        }
      },
      goEmailLogin() {
        alert(3)
      },
      getOtherQuery(query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>
